<template>
  <van-overlay
    :show="overlayShow"
    z-index="999">
    <div class="play-video-box">
      <div class="video-box">
        <video
          v-if="overlayShow"
          id="videoPlayer"
          ref="videoRef"
          class="video-js vjs-big-play-centered"
          muted></video>
      </div>
      <div
        class="close geek-icon"
        @click.stop="overlayShow = false">
        &#xe656;
      </div>
    </div>
  </van-overlay>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import route from '@/router';
// 引入Videojs
import Videojs from 'video.js';
import 'video.js/dist/video-js.css';
interface Props {
  videoUrl?: string;
  remove?: Function;
}

const videoRef = ref();
const overlayShow = ref(true);
const props = withDefaults(defineProps<Props>(), {
  videoUrl: '',
  remove: Function
});
const vPlayer = ref<any>(null);

const initVideo = (nowPlayVideoUrl: string) => {
  // 这些options属性也可直接设置在video标签上，见 muted
  const options = {
    // 设置自动播放
    autoplay: true,
    muted: false,
    // 显示播放的控件
    controls: true,
    controlBar: {},
    sources: [
      // 注意，如果是以option方式设置的src,是不能实现 换台的 (即使监听了nowPlayVideoUrl也没实现)
      {
        src: nowPlayVideoUrl,
        // 告诉videojs,这是一个hls流
        type: nowPlayVideoUrl.includes('m3u8') ? 'application/x-mpegURL' : 'video/mp4'
      }
    ]
  };
  // videojs的第一个参数表示的是，文档中video的id
  vPlayer.value = Videojs('videoPlayer', options, function onPlayerReady() {
    // console.log(myPlyer === this); // 这里返回的是true
  });
};
watch(
  () => overlayShow.value,
  (val) => {
    !val && props.remove();
    // 离开页面销毁
    vPlayer.value.dispose();
  }
);
// 路由变化时关闭组件
watch(
  () => route,
  () => {
    overlayShow.value = false;
    props.remove();
    vPlayer.value.dispose();
  },
  {
    deep: true
  }
);

onMounted(() => {
  initVideo(props.videoUrl);
});
</script>

<style lang="scss" scoped>
.play-video-box {
  position: relative;
  height: 100vh;
  z-index: 10;
  width: 750px;
  .video-box {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 100%;
    height: 100%;
    video {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
  }
  .close {
    font-size: 28px;
    color: #fff;
    position: absolute;
    right: 40px;
    top: 40px;
    z-index: 20;
  }
}
#videoPlayer {
  width: 100%;
  height: 100%;
  :deep(.vjs-big-play-button) {
    font-size: 2em !important;
    line-height: 2.3em !important;
    height: 2.5em !important;
    width: 2.5em !important;
    border-radius: 2em !important;
    background-color: #73859f;
    background-color: rgba(115, 133, 159, 0.5) !important;
    border-width: 0.15em !important;
    .vjs-icon-placeholder {
      font-size: 1.63em !important;
    }
  }
}
</style>
